/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.web.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.web.entity.WxAgents;
import com.jeeplus.modules.web.entity.YjAgentsDistribution;
import com.jeeplus.modules.web.mapper.WxAgentsMapper;
import com.jeeplus.modules.web.service.YjAgentsDistributionService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 年分销商比例Controller
 * @author rongjie
 * @version 2017-10-08
 */
@Controller
@RequestMapping(value = "${adminPath}/web/yjAgentsDistribution")
public class YjAgentsDistributionController extends BaseController {

	@Autowired
	private YjAgentsDistributionService yjAgentsDistributionService;
	@Autowired
	private WxAgentsMapper wxAgentsMapper;

	@ModelAttribute
	public YjAgentsDistribution get(@RequestParam(required=false) String id) {
		YjAgentsDistribution entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = yjAgentsDistributionService.get(id);
		}
		if (entity == null){
			entity = new YjAgentsDistribution();
		}
		return entity;
	}

	/**
	 * 年分销商比例列表页面
	 */
 	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/web/yjAgentsDistributionList";
	}

		/**
	 * 年分销商比例列表数据
	 */
	@ResponseBody
 	@RequestMapping(value = "data")
	public Map<String, Object> data(YjAgentsDistribution yjAgentsDistribution,
									HttpServletRequest request,
									HttpServletResponse response, Model model) {
		User currentUser = UserUtils.getUser();
		if (!currentUser.getId().equals("1")) {
			WxAgents wxAgents = new WxAgents();
			wxAgents.setUserName(currentUser.getMobile());
			wxAgents = wxAgentsMapper.findUniqueByProperty("username", currentUser.getMobile());
			yjAgentsDistribution.setAgents(wxAgents);
		}
		Page<YjAgentsDistribution> page = yjAgentsDistributionService.findPage(new Page<YjAgentsDistribution>(request, response), yjAgentsDistribution);
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑年分销商比例表单页面
	 */
 	@RequestMapping(value = "form")
	public String form(YjAgentsDistribution yjAgentsDistribution, Model model) {
		model.addAttribute("yjAgentsDistribution", yjAgentsDistribution);
		if(StringUtils.isBlank(yjAgentsDistribution.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		return "modules/web/yjAgentsDistributionForm";
	}

	/**
	 * 保存年分销商比例
	 */
 	@RequestMapping(value = "save")
	public String save(YjAgentsDistribution yjAgentsDistribution, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, yjAgentsDistribution)){
			return form(yjAgentsDistribution, model);
		}
		if(!StringUtils.isEmpty(yjAgentsDistribution.getId())){
		YjAgentsDistribution yjAgentsDistributions=yjAgentsDistributionService.get(yjAgentsDistribution.getId());
		if(!yjAgentsDistributions.getAgentsDistributionA().equals("0")){
			if(!yjAgentsDistributions.getAgentsDistributionA().equals(yjAgentsDistribution.getAgentsDistributionA())){
				yjAgentsDistributions.setTime(new Date());
			}
		}
		}else{
			yjAgentsDistribution.setTime(new Date());

		}

		//新增或编辑表单保存
		yjAgentsDistributionService.save(yjAgentsDistribution);//保存
		addMessage(redirectAttributes, "保存年分销商比例成功");
		return "redirect:"+Global.getAdminPath()+"/web/yjAgentsDistribution/?repage";
	}

	/**
	 * 删除年分销商比例
	 */
	@ResponseBody
 	@RequestMapping(value = "delete")
	public AjaxJson delete(YjAgentsDistribution yjAgentsDistribution, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		yjAgentsDistributionService.delete(yjAgentsDistribution);
		j.setMsg("删除年分销商比例成功");
		return j;
	}

	/**
	 * 批量删除年分销商比例
	 */
	@ResponseBody
 	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			yjAgentsDistributionService.delete(yjAgentsDistributionService.get(id));
		}
		j.setMsg("删除年分销商比例成功");
		return j;
	}

	/**
	 * 导出excel文件
	 */
	@ResponseBody
     @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(YjAgentsDistribution yjAgentsDistribution, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "年分销商比例"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<YjAgentsDistribution> page = yjAgentsDistributionService.findPage(new Page<YjAgentsDistribution>(request, response, -1), yjAgentsDistribution);
    		new ExportExcel("年分销商比例", YjAgentsDistribution.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出年分销商比例记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("web:yjAgentsDistribution:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<YjAgentsDistribution> list = ei.getDataList(YjAgentsDistribution.class);
			for (YjAgentsDistribution yjAgentsDistribution : list){
				try{
					yjAgentsDistributionService.save(yjAgentsDistribution);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条年分销商比例记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条年分销商比例记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入年分销商比例失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/web/yjAgentsDistribution/?repage";
    }

	/**
	 * 下载导入年分销商比例数据模板
	 */
	@RequiresPermissions("web:yjAgentsDistribution:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "年分销商比例数据导入模板.xlsx";
    		List<YjAgentsDistribution> list = Lists.newArrayList();
    		new ExportExcel("年分销商比例数据", YjAgentsDistribution.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/web/yjAgentsDistribution/?repage";
    }

}